<template>
    <div class="boxContentCss">
            <EdCreateCard :title="isUpdate ? '编辑商家' : '新建商家' ">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div style="padding: 24px 15px 8px 15px;">
                    <el-form :model="form" ref="formRef" label-position='right' label-width="150px" size="small">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="店铺名称"  prop="merchantName" :rules="$validate.validates({required:true,msg:'店铺名称不能为空'})">
                                    <el-input v-model="form.merchantName" placeholder="请输入店铺名称" maxlength="20"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="店铺地址" prop="address" :rules="$validate.validates({required:true,msg:'店铺地址不能为空'})">
                                    <el-input v-if="form.address" style="width: calc(100% - 100px)" v-model="form.address" placeholder="请输入"  maxlength="50"></el-input>
                                    <span class="colorMainTwo marginLeft8" @click="showMap">
                                        <i class="el-icon-location-information fontSize16"></i>
                                        <span class="marginLeft2 cursorPointer">地图定位</span>
                                    </span>
                            </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="服务范围" prop="village" :rules="$validate.validates({required:true,msg:'服务范围不能为空'})" >
                                    <EdSelect v-model="form.village" :multiple="projectNameParams.multiple" :selectParams="projectNameParams"  style="width:100%" @input="projectValueChange" ></EdSelect>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="商家姓名" prop="name" :rules="$validate.validates({required:true,msg:'商家姓名不能为空'})">
                                    <el-input v-model="form.name" placeholder="请输入商家姓名" maxlength="11"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="商家手机号" prop="mobile" :rules="$validate.validates({required:true,msg:'商家手机号不能为空',type:'mobile'})">
                                    <el-input v-model="form.mobile" placeholder="请输入商家手机号" maxlength="11"></el-input>
                                </el-form-item>
                             </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="登录账号" prop="loginName" :rules="$validate.validates({required:true,msg:'登录账号不能为空',type:'account'})">
                                    <el-input v-model="form.loginName" :rows="4" :disabled="isUpdate" placeholder="请输入登录账号" maxlength="50" minlength="8"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="所在行业" prop="industryId" :rules="$validate.validates({required:true,msg:'所在行业不能为空'})">
                                    <EdCascader v-model="form.industryId" :cascaderParams="selectIndustryParams" ref="cascader" style="width:100%" @change-emit-label="IndustryValueChange"></EdCascader>
                                </el-form-item>
                             </el-col>
                        </el-row>   
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="结算账户" prop="settlementAccount" >
                                    <el-input v-model="form.settlementAccount" placeholder="请输入" maxlength="11"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="营业执照注册号" prop="licenseNo" :rules="$validate.validates({required:true,msg:'营业执照注册号不能为空',type:'license'})">
                                    <el-input v-model="form.licenseNo" placeholder="请输入营业执照注册号" maxlength="18"></el-input>
                                </el-form-item>
                             </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-form-item label="营业执照" prop="licensePic" >
                                    <el-upload
                                            class="business-uploader-single-313  avatar-uploader"
                                            accept="image/*"
                                            :action="action"
                                            :headers="headers"
                                            :disabled="uploadBoolean"
                                            :show-file-list="false"
                                            :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                        <el-image v-if="form.licensePic" :src="form.licensePic" fit="contain"></el-image>
                                        <div v-else >
                                            <i class="el-icon-plus avatar-uploader-icon"></i>
                                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65); margin: 0 0 8px 0;line-height: 1">上传图片</div>
                                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65);line-height: 1">大小不超过2M</div>
                                        </div>
                                        <!-- 页面增加删除和预览 -->
                                        <span v-if="form.licensePic" class="el-upload-list__item-actions">
                                            <span class="upload-icon">
                                                <span class="el-uploads-span" style="margin-right: 10px;" @click="oploadImgPre">
                                                    <i class="el-icon-zoom-in"></i>
                                                </span>
                                                <span class="el-upload-span" @click="oploadImgDel">
                                                    <i class="el-icon-delete"></i>
                                                </span>
                                            </span>
                                        </span>
                                        <el-dialog title="图片预览" :visible.sync="dialogVisible">
                                            <img width="100%" :src="dialogImageUrl" alt="">
                                        </el-dialog>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>       
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="门头照片" prop="storePic">
                                    <el-upload
                                            class="business-uploader-single-313"
                                            accept="image/*"
                                            :action="action"
                                            :headers="headers"
                                            :disabled="uploadStoreBoolean"
                                            :show-file-list="false"
                                            :on-success="handleAvatarLogoSuccess"
                                            :before-upload="beforeAvatarLogoUpload">
                                        <el-image v-if="form.storePic" :src="form.storePic" fit="contain"></el-image>
                                        <div v-else>
                                            <i class="el-icon-plus avatar-uploader-icon"></i>
                                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65); margin: 0 0 8px 0;line-height: 1">上传图片</div>
                                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65);line-height: 1">大小不超过2M</div>
                                        </div>
                                        <!-- 页面增加删除和预览 -->
                                        <span v-if="form.storePic" class="el-upload-list__item-actions">
                                            <span class="upload-icon">
                                                <span class="el-uploads-span" style="margin-right: 10px;" @click="uploadSroreImgPre">
                                                    <i class="el-icon-zoom-in"></i>
                                                </span>
                                                <span class="el-upload-span" @click="uploadStoreImgDel">
                                                    <i class="el-icon-delete"></i>
                                                </span>
                                            </span>
                                        </span>
                                        <el-dialog title="图片预览" :visible.sync="dialogStoreVisible">
                                            <img width="100%" :src="dialogStoreImageUrl" alt="">
                                        </el-dialog>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-form-item class="paddingBottom145 btnClass1">
                                    <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" :loading="disabled">保 存</el-button>
                                    <el-button class="ed-button ed_white_bottom" @click="reset()">重 置</el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                     
                </div>
            </EdCreateCard>

        <ed-map ref="edMap" @setAddress="setAddress" :edMapObj="edMapObj"></ed-map>
    </div>
</template>

<script>
    import EdMap from "../../../components/EdMap.vue";
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCascader from 'src/components/EdCascader.vue'
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import {addMerchant ,merchantDetail ,updateBase,projectList,getIndustry} from "./api";
    import {getToken} from 'src/utils/auth'
    export default {
        name: "BusinessCreate",
        components:{EdMap,EdCreateCard,EdSelect,EdCreateCard,EdCascader},
        data(){
            return{
                form:{
                    merchantName:"",
                    address:"",
                    village:[],
                    name:"",
                    mobile:"",
                    loginName:"",
                    industryId:'',
                    industryName:"",
                    settlementAccount: '',
                    licenseNo:'',
                    licensePic: '',
                    lngLat:'',
                    storePic:''
                    // userId:''
                },
                projectNameParams:{
                    placeholder:"请选择",
                    options: [],
                    multiple:true
                },
                selectIndustryParams:{
                    placeholder:"请选择",
                    options: [],
                    props: {value: 'id', label: 'name', checkStrictly: false,emitPath:false}
                },
                action:"",
                headers:{
                    RdAuthorization: getToken()
                },
                upFile:new FormData(),
                disabled:false,
                isUpdate:false,
                edMapObj:{},
                edUploadForm:{
                    widthClass313:true,
                    size:true
                },
                mobile:null,
                dialogImageUrl:'',
                dialogVisible: false,
                uploadBoolean:false,
                dialogStoreImageUrl:'',
                dialogStoreVisible:false,
                uploadStoreBoolean:false,
            }
        },
        created() {},
        activated(){
            this.initDic()
            this.action = this.$baseApi + "/file/upload";
            if(this.$route.query.id){
                this.isUpdate = true;
                this.merchantDetail()
            }else {
                this.isUpdate = false;
            }
            getIndustry().then((res) =>{
                // let arr = [];
                // arr.push(res.data)
                // this.selectIndustryParams.options = arr
                this.$set(this.selectIndustryParams,'options', res.data)
            })
        },
        deactivated() {
            this.form = {
                merchantName:"",
                address:"",
                village:[],
                name:"",
                mobile:"",
                loginName:"",
                industryId:'',
                industryName:"",
                settlementAccount: '',
                licenseNo:'',
                licensePic: '',
                lngLat:'',
                userId:'',
                storePic:''
            }
            // this.multipleSelection=[]
            this.$refs['formRef'].resetFields();
        },
        methods:{
            initDic(){
                projectList({page:1,pageSize:999999}).then(response => {
                    if(response.success) {
                        let options = response.data.records.map(x=>{return {label:x.villageName,value:x.villageId}})
                        this.projectNameParams.options=options
                    }
                })
            },
            merchantDetail(){
                getIndustry().then((res) =>{
                    this.$set(this.selectIndustryParams,'options', res.data)
                    merchantDetail({id:this.$route.query.id}).then(response => {
                        if(response.success) {
                            this.uploadBoolean = true
                            this.uploadStoreBoolean = true
                            this.form = {
                                id:this.$route.query.id,
                                merchantName:response.data.merchantName,
                                address:response.data.address,
                                village:response.data.village,
                                mobile:response.data.mobile,
                                name:response.data.name,
                                loginName:response.data.loginName,
                                industryId:parseInt(response.data.industryId),
                                industryName:response.data.industryName,
                                settlementAccount:response.data.settlementAccount,
                                licenseNo:response.data.licenseNo,
                                licensePic:response.data.licensePic,
                                storePic:response.data.storePic,
                                lngLat:response.data.lngLat,
                            };
                            this.edMapObj.lngLat = response.data.lngLat;
                            this.edMapObj.address = response.data.address
                            this.form.village=this.form.village.toString().split(',')
                        }
                    })
                })
            },
            getSelectName(val, data){
                let name_1 = '', name_2 = '', fullName='';
                data&&data.forEach((item_1, index_1)=>{
                    item_1.children.forEach((item_2, index_2)=>{
                        if(item_2.id == val){
                            name_2 = item_2.name
                            name_1 = item_1.name
                            fullName = name_1 + '/ '+ name_2
                        } 
                    })
                })
                console.log('fullName',fullName);
                return fullName
            },
            showMap(){
                this.$refs.edMap.showMap()
            },
            // 营业执照上传成功
            handleAvatarSuccess(file){
                this.$set(this.form,"licensePic",file.data);
                if(this.form.licensePic){
                    this.uploadBoolean = true
                }
            },
            // 营业执照上传
            beforeAvatarUpload(file){
                const isLt5M = file.size / 1024 /1024 < 2;
                if (!isLt5M) {
                    this.$message.error({message: '上传文件大小不能超过 2MB!', center: true});
                }
                return isLt5M;
            },
             // 营业执照图片 预览
            oploadImgPre(){
                this.dialogVisible = true
                this.dialogImageUrl = this.form.licensePic;
            },
            // 营业执照图片 删除
            oploadImgDel(){
                this.form.licensePic = ''
                let _this= this
                setTimeout(function(){
                    // console.log(_this)
                    _this.uploadBoolean = false
                },1000)
            },

            // 门头照上传成功
            handleAvatarLogoSuccess(file){
                this.$set(this.form,"storePic",file.data);
                if(this.form.storePic){
                    this.uploadStoreBoolean = true
                }
            },
            // 门头照上传
            beforeAvatarLogoUpload(file){
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 2MB!');
                }
                return isLt2M;
            },
            // 门头照预览
            uploadSroreImgPre(){
                this.dialogStoreVisible = true
                this.dialogStoreImageUrl = this.form.storePic;
            },
            // 门头照删除
            uploadStoreImgDel(){
                this.form.storePic = ''
                let _this= this
                setTimeout(function(){
                    // console.log(_this)
                    _this.uploadStoreBoolean = false
                },1000)
            },
            onSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if(this.isUpdate){
                            // 编辑接口
                            this.disabled = true;
                            let query = this.form.copy();
                            query.userId = this.$route.query.userId
                            updateBase(query).then(response => {
                                if(response.code == 20000) {
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '保存成功',
                                        center: true,
                                        duration: 2000,
                                    })
                                    this.$router.back()
                                    this.$refs.table.load()
                                    // window.setTimeout(() => {
                                    //     this.$utilsSet.goBack(this.$router);
                                    // }, 600)
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }else {
                            // 新增接口
                            addMerchant(this.form).then(response => {
                                if(response.success) {
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '添加成功',
                                        center: true,
                                        duration: 2000,
                                    })
                                    this.$router.back()
                                    window.setTimeout(() => {
                                        this.$utilsSet.goBack(this.$router);
                                    }, 600)
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }
                    }
                })
            },
            setAddress(data){
                this.edMapObj = data
                // console.log('data',data);
                this.form.address = data.address;
                this.form.lngLat = data.lnglat.lng + ',' +data.lnglat.lat;
                this.$refs.formRef.validateField("address")
            },
            reset(){
                this.form = {
                    merchantName:"",
                    address:"",
                    village:[],
                    name:"",
                    mobile:"",
                    industryId:'',
                    industryName:"",
                    settlementAccount: '',
                    licenseNo:'',
                    licensePic: '',
                    storePic:'',
                    loginName:this.form.loginName,
                    id:this.$route.query.id ? this.$route.query.id : null,
                };
                // this.$refs.formRef.resetFields();
            },
            IndustryValueChange(row){
                console.log('row',row);
                this.form.industryName = row
            },
            projectValueChange(row){
                // console.log('row',row);
                let options = this.projectNameParams.options.find(x=>x.value==row)
                return options ? options.label : ''
            }
        }
    }
</script>

<style lang="scss" scoped>
.avatar-uploader >>>.el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .el-upload-list__item-actions:hover {
        opacity: 1;
    }
    .el-upload-list__item-actions:hover span {
        display: inline-block
    }
    .avatar-uploader >>>.el-upload:hover {
        border-color: #409EFF;
    }
    .upload-icon {
        .el-upload-list__item-actions {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        cursor: default;
        text-align: center;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0,0,0,.5);
        transition: opacity .3s;
    }
        position: absolute;
        top: 50%;
        
        margin-left: -174px;
        margin-top: -18px;
    }
    .el-uploads-span {
        position: static;
        font-size: inherit;
        color: inherit;
    }
    .el-icon-zoom-in {
        width: 25px;
        height: 25px;
        color: #FFFFFF;
        font-weight: bold;
    }
    .el-icon-delete {
       width: 25px;
       height: 25px;
       color: #FFFFFF;
       font-weight: bold;
    }
</style>